<?php

namespace app\common\model\banxi\core;

use app\common\enums\AccountTypeEnum;
use app\common\enums\BrokerageBusinessTypeEnum;
use app\common\enums\core\RefundStatusEnum;
use app\common\model\common\BaseModel;
use app\common\service\core\CoreAccountDataService;
use app\common\service\SnowflakeService;
use ba\Exception;
use think\db\exception\PDOException;
use think\exception\ValidateException;
use think\model\concern\SoftDelete;

/**
 * 账户课时表
 */
class CoreBrokerageRw extends BaseModel
{
    use SoftDelete;

    protected $name = 'banxi_core_brokerage_rw';

    protected $autoWriteTimestamp = true;

    protected $deleteTime = 'del';

    protected $defaultSoftDelete = 0;

    protected $append = [
        'accountTypeCn',
        'businessTypeCn',
        'refundStatusCn'
    ];

    protected $type = [
        'id' => 'string',
        'del' => 'string',
        'tradeType' => 'boolean',
        'createTime' => 'timestamp:Y-m-d H:i:s',
        'updateTime' => 'timestamp:Y-m-d H:i:s',
    ];

    //-----------------------------------------------------------------------------------
    //-                                  获取器                                        -
    //-----------------------------------------------------------------------------------

    public function getAccountTypeCnAttr($value, $data): string
    {
        $value = $value ?: ($data['accountType'] ?? '');
        return (new AccountTypeEnum())->getDescription($value) ?? '';
    }

    public function getBusinessTypeCnAttr($value, $data)
    {
        $value = $value ?: ($data['businessType'] ?? '');
        return (new BrokerageBusinessTypeEnum())->getDescription($value) ?? '';
    }

    public function getRefundStatusCnAttr($value, $data)
    {
        $value = $value ?: ($data['refundStatus'] ?? '');
        return (new RefundStatusEnum())->getDescription($value) ?? '';
    }

    //-----------------------------------------------------------------------------------
    //-                                  处理方法                                        -
    //-----------------------------------------------------------------------------------

    public function getTradeType($businessType)
    {
        return (new BrokerageBusinessTypeEnum())->getTradeType($businessType) ?? '';
    }

    public function refundAccount($brokerageRwId, $describe)
    {
        try {
            $brokerageRw = $this->where('id', $brokerageRwId)->find();
            if (empty($brokerageRw)) {
                throw new ValidateException('佣金流水不存在');
            }
            if ($brokerageRw['refundStatus'] == RefundStatusEnum::E2 || $brokerageRw['refundStatus'] == RefundStatusEnum::E3) {
                return true;
            }
            $refundStatus = $brokerageRw['refundStatus'];
            $snowflakeService = new SnowflakeService(1, 1);
            $refundFlowId = $snowflakeService->nextId();
            $trade = [
                'id' => $refundFlowId,
                'accountId' => $brokerageRw['accountId'],
                'accountType' => $brokerageRw['accountType'],
                'organizationId' => $brokerageRw['organizationId'],
                'businessType' => BrokerageBusinessTypeEnum::E3,
                'businessId' => $brokerageRw['businessId'],
                'value' => $brokerageRw['value'],
                'describe' => $describe
            ];
            $res = $this->updateAccount($trade);
            if (!$res) {
                throw new ValidateException('更新佣金流水失败');
            }
            $this->update([
                'refundStatus' => RefundStatusEnum::E3,
                'refundAmount' => $brokerageRw->value,
                'refundFlowId' => $refundFlowId
            ], ['id' => $brokerageRwId, 'refundStatus' => $refundStatus]);
        } catch (ValidateException|PDOException|Exception $e) {
            throw new ValidateException($e->getMessage());
        }
        return false;
    }
    public function updateAccount($trade)
    {
        $brokerageRwId = $trade['id'] ?? '';
        if (!$brokerageRwId) {
            $snowflakeService = new SnowflakeService(1, 1);
            $trade['id'] = $snowflakeService->nextId();
        }
        $accountId = $trade['accountId'];
        $accountType = $trade['accountType'];
        $businessType = $trade['businessType'];
        $tradeType = $this->getTradeType($businessType);
        $trade['tradeType'] = $tradeType;
        $accountDataService = new CoreAccountDataService();
        $accountData = $accountDataService->getByAccountIdAndType($accountId, $accountType);
        if (!$accountData){
            throw new ValidateException($accountDataService->getError());
        }
        $beforeValue = $accountData['brokerageAmount'];
        if ($tradeType) {
            $afterValue = $beforeValue + $trade['value'];
        } else {
            $afterValue = $beforeValue - $trade['value'];
            if ($afterValue < 0) {
                throw new ValidateException('佣金余额不足');
            }
        }
        $cnt = $accountDataService->updateBrokerage($accountId, $accountType, $beforeValue, $afterValue);
        if (!$cnt) {
            throw new ValidateException('更新佣金余额失败');
        }
        $trade['beforeValue'] = $beforeValue;
        $trade['afterValue'] = $afterValue;
        $this->save($trade);
        return true;
    }

    //-----------------------------------------------------------------------------------
    //-                                   模型关联                                       -
    //-----------------------------------------------------------------------------------


}